<template>
  <el-dialog
    v-model="visible"
    width="800px"
    :close-on-click-modal="false"
    append-to-body
    class="unified-dialog detail-dialog-simple-json"
    top="5vh"
  >
    <template #header>
      <DialogHeader
        icon="Document"
        title="简单带JSON数据的详情示例"
        description="包含JSON数据时，在 el-descriptions 中使用 pre 标签展示JSON"
        type="primary"
      />
    </template>
    
    <div v-if="data" class="dialog-content">
      <el-descriptions :column="2" border size="default">
        <!-- 基本信息 -->
        <el-descriptions-item label="时间" label-class-name="detail-label">
          {{ data.message_timestamp || data.created_at || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="服务名" label-class-name="detail-label">
          <el-tag size="small" type="info">{{ data.service_name || 'yc-cps-api' }}</el-tag>
        </el-descriptions-item>
        
        <el-descriptions-item label="接口路径" :span="2" label-class-name="detail-label">
          <div class="detail-text">{{ data.api_path || data.topic_name || '-' }}</div>
        </el-descriptions-item>
        
        <el-descriptions-item label="HTTP方法" label-class-name="detail-label">
          <el-tag size="small" type="primary">POST</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态码" label-class-name="detail-label">
          <el-tag size="small" type="success">200</el-tag>
        </el-descriptions-item>
        
        <el-descriptions-item label="响应时间" label-class-name="detail-label">
          <span>807ms</span>
        </el-descriptions-item>
        <el-descriptions-item label="状态" label-class-name="detail-label">
          <el-tag size="small" type="success">成功</el-tag>
        </el-descriptions-item>
        
        <el-descriptions-item label="Trace ID" label-class-name="detail-label">
          <div class="detail-trace">
            <span>{{ data.trace_id || 'b7fcb1584e954c2e8bdee35048bcddc3' }}</span>
            <el-button 
              size="small" 
              text 
              type="primary"
              @click="copyToClipboard(data.trace_id || 'b7fcb1584e954c2e8bdee35048bcddc3', 'Trace ID')"
              :icon="DocumentCopy"
            >
              复制
            </el-button>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="日志消息" label-class-name="detail-label">
          <div class="detail-message">{{ data.message || 'API access completed successfully' }}</div>
        </el-descriptions-item>
        
        <!-- JSON字段：请求体 -->
        <el-descriptions-item label="请求体" :span="2" label-class-name="detail-label">
          <div class="detail-json">
            <el-button 
              v-if="data.request_body || data.latest_message"
              size="small" 
              text 
              type="primary"
              @click="copyToClipboard(getRawJsonValue(data.request_body || data.latest_message), '请求体')"
              :icon="DocumentCopy"
              style="float: right;"
            >
              复制
            </el-button>
            <pre v-if="data.request_body || data.latest_message" class="json-content">
              {{ formatJsonString(data.request_body || data.latest_message) }}
            </pre>
            <span v-else>-</span>
          </div>
        </el-descriptions-item>
        
        <!-- JSON字段：响应体 -->
        <el-descriptions-item label="响应体" :span="2" label-class-name="detail-label">
          <div class="detail-json">
            <el-button 
              v-if="data.response_body || defaultResponseBody"
              size="small" 
              text 
              type="primary"
              @click="copyToClipboard(getRawJsonValue(data.response_body || defaultResponseBody), '响应体')"
              :icon="DocumentCopy"
              style="float: right;"
            >
              复制
            </el-button>
            <pre v-if="data.response_body || defaultResponseBody" class="json-content">
              {{ formatJsonString(data.response_body || defaultResponseBody) }}
            </pre>
            <span v-else>-</span>
          </div>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed } from 'vue'
import { ElMessage } from 'element-plus'
import { DocumentCopy } from '@element-plus/icons-vue'
import DialogHeader from '@/components/DialogHeader.vue'
import { copyToClipboard as copyTextUtil } from '@/utils/clipboard'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue'])

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 默认响应体（演示数据）
const defaultResponseBody = {
  code: 1,
  message: '操作成功'
}

// 格式化JSON字符串（用于显示）
const formatJsonString = (value, indent = 2) => {
  if (!value) return '-'
  
  try {
    // 如果是字符串，尝试解析为JSON对象再格式化
    if (typeof value === 'string') {
      try {
        const parsed = JSON.parse(value)
        return JSON.stringify(parsed, null, indent)
      } catch (e) {
        // 如果不是有效的JSON字符串，直接返回
        return value
      }
    }
    
    // 如果是对象，转成格式化的字符串
    return JSON.stringify(value, null, indent)
  } catch (error) {
    // 如果所有尝试都失败，返回原始值
    return typeof value === 'string' ? value : String(value)
  }
}

// 获取原始 JSON 值（用于复制）
const getRawJsonValue = (value) => {
  if (!value) return ''
  
  try {
    // 如果是字符串，直接返回
    if (typeof value === 'string') {
      return value
    }
    
    // 如果是对象，转成格式化的字符串
    return JSON.stringify(value, null, 2)
  } catch (error) {
    return typeof value === 'string' ? value : String(value)
  }
}

// 复制到剪贴板
const copyToClipboard = async (text, label = '') => {
  try {
    await copyTextUtil(text, label)
    ElMessage.success(label ? `${label}已复制到剪贴板` : '已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.detail-label {
  font-weight: 600;
  color: #606266;
}

.detail-text {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  color: #303133;
  word-break: break-all;
}

.detail-trace {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.detail-trace span {
  flex: 1;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  color: #303133;
  word-break: break-all;
}

.detail-message {
  font-size: 13px;
  color: #606266;
  line-height: 1.6;
}

.detail-json {
  position: relative;
}

.json-content {
  margin: 8px 0 0 0;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-family: 'Courier New', 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.6;
  max-height: 300px;
  overflow-y: auto;
  white-space: pre-wrap;
  word-break: break-all;
  color: #303133;
}
</style>

